package com.liuceng.mps.mapper.typehanders;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@MappedJdbcTypes(JdbcType.OTHER)
@MappedTypes(JSONObject[].class)
public class JSONArrayTypeHandler extends BaseTypeHandler<JSONObject[]> {

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, JSONObject[] parameter,
      JdbcType jdbcType) throws SQLException {
    Connection c = ps.getConnection();
    List<String> pList = Arrays.asList(parameter).stream().map(json -> json.toJSONString())
        .collect(Collectors.toList());
    Array inArray = c.createArrayOf("jsonb", pList.toArray());
    ps.setArray(i, inArray);
  }

  @Override
  public JSONObject[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
    Array outputArray = rs.getArray(columnName);
    if (outputArray == null) {
      return null;
    }
    String[] resarr = (String[]) outputArray.getArray();
    List<JSONObject> jList = Arrays.asList(resarr).stream().map(string -> JSON.parseObject(string))
        .collect(Collectors.toList());
    //
    return jList.toArray(new JSONObject[0]);
  }

  @Override
  public JSONObject[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    Array outputArray = rs.getArray(columnIndex);
    if (outputArray == null) {
      return null;
    }
    String[] resarr = (String[]) outputArray.getArray();
    List<JSONObject> jList = Arrays.asList(resarr).stream().map(string -> JSON.parseObject(string))
        .collect(Collectors.toList());
    return jList.toArray(new JSONObject[0]);
  }

  @Override
  public JSONObject[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    Array outputArray = cs.getArray(columnIndex);
    if (outputArray == null) {
      return null;
    }
    String[] resarr = (String[]) outputArray.getArray();
    List<JSONObject> jList = Arrays.asList(resarr).stream().map(string -> JSON.parseObject(string))
        .collect(Collectors.toList());
    return jList.toArray(new JSONObject[0]);
  }


}
